from django.shortcuts import render
from django.http import HttpResponse
import datetime

# Create your views here.
from rest_framework import status
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from rest_framework.views import APIView

from utils.OrderQueryPay import OrderQueryPay
from utils.WeChatRefund import WeChatRefundPay
from utils.WechatPay import WeChatPay
from orders.models import OrderInfo,ReturnDetail

def get_nonce_str():
    import uuid

    return str(uuid.uuid4()).replace('-', '')

class WxPayView(APIView):
    """
    统一下单支付接口
    """
    permission_classes = [IsAuthenticated]

    def get(self, request):
        """
        获取支付链接
        """
        # 判断订单信息是否正确
        order_id = request.query_params.get('order_id')
        body = request.query_params.get('body')
        total_fee = request.query_params.get('total_fee')
        try:
            order = OrderInfo.objects.get(order_id=order_id, user=request.user,
                                          status=1)
        except OrderInfo.DoesNotExist:
            return Response({'message': '订单信息有误'}, status=status.HTTP_400_BAD_REQUEST)

        # 调用微信支付接口
        wxpay = WeChatPay(
            order_id=order_id,
            body=body,
            total_fee=int(float(total_fee) * 100),  # 单位为分
            nonce_str=get_nonce_str(),
            openid=self.request.user.username
        )
        result = wxpay.re_finall()
        return Response(result)


class WxPayRefundView(APIView):
    """
    退款接口
    """
    permission_classes = [IsAuthenticated]

    def get(self, request):
        """
        获取支付链接
        """
        # 判断订单信息是否正确
        order_id = request.query_params.get('order_id')
        refund_id = request.query_params.get('refund_id')
        total_fee = request.query_params.get('total_fee')
        refund_fee = request.query_params.get('refund_fee')
        try:
            order = OrderInfo.objects.get(order_id=order_id)
        except OrderInfo.DoesNotExist:
            return Response({'message': '订单信息有误，退款失败'}, status=status.HTTP_400_BAD_REQUEST)
        if self.request.user.role in (0,1):
            # 调用微信支付接口
            wxrefundpay = WeChatRefundPay(
                order_id=order_id,
                refund_id=refund_id,
                total_fee=int(float(total_fee) * 100),
                refund_fee=int(float(refund_fee) * 100),
                nonce_str=get_nonce_str(),
            )
            result = wxrefundpay.get_result()
            returndetail = ReturnDetail.objects.get(return_numbers=refund_id)
            returndetail.order_goods_id.is_return = 8
            returndetail.order_goods_id.save()
            if returndetail.check_results  in (6,9): # 退货途中
                returndetail.check_results = 12
                returndetail.save()
            return Response(result)
        else:
            return Response({'Resultcode':0,'message':'权限不足'},status=status.HTTP_403_FORBIDDEN)

class Pay_MoneyView(APIView):
    permission_classes = [IsAuthenticated]

    def post(self, request):
        order_id = request.data.get('order_id')
        try:
            orderinfo = OrderInfo.objects.get(order_id=order_id)
        except:
            return Response({"massage": "查询订单不存在"})
        # 调用查询订单接口

        wxrefundpay = OrderQueryPay(
            order_id=order_id,
            nonce_str=get_nonce_str(),
        )
        result = wxrefundpay.get_pay_result()
        if result['pay_result']  == 'SUCCESS':
            orderinfo.status = 2
            orderinfo.pay_time = datetime.datetime.now()
            orderinfo.transaction_id = result['transaction_id']
            orderinfo.save()
            return Response({'ResultCode':1,'message':'付款成功'})
        else:
            return Response({'ResultCode':0,'message':'付款失败'})
